package com.example.myspringai.voice;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.security.cert.X509Certificate;

public class IntellaVoiceApi {

    private static final String API_URL = "https://api.intella-voice.com/api/accounts/";
    private static final String ACCOUNT_ID = "be216b3f-c48c-4b5f-b455-21635fb36f41";
    private static final String API_TOKEN = "jbJF01a/7EW7vD3fk3AQ/Q=="; // Replace with your actual API token

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Administrator\\Desktop\\standard-dataset\\standard_darija\\darija_01\\darija_01.mp3";

        try {
            String requestId = uploadFile(filePath);
            if (requestId != null) {
                getTranscription(requestId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String uploadFile(String filePath) throws IOException {
        CloseableHttpClient httpClient = createHttpClient();
        HttpPost uploadFile = new HttpPost(API_URL + ACCOUNT_ID + "/requests");

        // Set headers
        uploadFile.setHeader("x-ApiToken", API_TOKEN);
        uploadFile.setHeader("Content-Type", "multipart/form-data");

        // Build the file entity
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, filePath);
        builder.addTextBody("fileName", "darija_01.mp3", ContentType.TEXT_PLAIN);
        builder.addTextBody("timestamp", "0", ContentType.TEXT_PLAIN);
        builder.addTextBody("noOfSpeakers", "1", ContentType.TEXT_PLAIN);

        HttpEntity multipart = builder.build();
        uploadFile.setEntity(multipart);

        CloseableHttpResponse response = httpClient.execute(uploadFile);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            String responseString = EntityUtils.toString(responseEntity);
            System.out.println("Upload response: " + responseString);

            // Extract requestId from the response (assuming response is JSON and contains requestId)
            // You may need a JSON parser library like Jackson or Gson to parse the response
            // For simplicity, let's assume the response contains requestId directly
            // In real implementation, parse the JSON response to get the requestId
            return "extracted_request_id";
        }

        response.close();
        return null;
    }

    private static void getTranscription(String requestId) throws IOException {
        CloseableHttpClient httpClient = createHttpClient();
        HttpGet getTranscription = new HttpGet(API_URL + ACCOUNT_ID + "/requests/" + requestId);

        // Set headers
        getTranscription.setHeader("x-ApiToken", API_TOKEN);

        HttpResponse response = httpClient.execute(getTranscription);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            String responseString = EntityUtils.toString(responseEntity);
            System.out.println("Transcription response: " + responseString);
        }
    }

    private static CloseableHttpClient createHttpClient() throws IOException {
        try {
            SSLContext sslContext = SSLContextBuilder.create()
                    .loadTrustMaterial(new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] chain, String authType) {
                            return true;
                        }
                    }).build();

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);

            return HttpClients.custom()
                    .setSSLSocketFactory(sslSocketFactory)
                    .build();
        } catch (Exception e) {
            throw new IOException("Failed to create HTTP client with SSL support", e);
        }
    }
}
